﻿using System;
using NLog;
using Quadrant.domain.DB;

namespace Quadrant.domain.Helpers
{
    public abstract class BaseServices : IDisposable
    {
        private QuadrantContext _dbContext;
        private readonly Boolean _noDispose;

        protected QuadrantContext DB
        {
            get { return this._dbContext ?? (this._dbContext = new QuadrantContext()); }
        }

        protected Logger Logger;

        protected BaseServices(){}

        protected BaseServices(QuadrantContext context)
        {
            this._dbContext = context;
            this._noDispose = true;
        }

        protected BaseServices(QuadrantContext context,Logger log=null)
            :this(context)
        {
            this.Logger = log;
        }

        protected BaseServices(Logger log = null)
        {
            this.Logger = log;
        }

        public void Dispose()
        {
            if (!this._noDispose && this._dbContext != null)
            {
                try
                {
                    this._dbContext.Database.Connection.Close();
                    this._dbContext.Dispose();
                }
                finally
                {
                    this._dbContext = null;
                }
            }
        }
    }
}
